// Copyright (c) 2007 Readify Pty. Ltd.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.

using System;
using System.Collections.Generic;
using System.Text;
using Microsoft.TeamFoundation.Build.Proxy;
using BuildVirtualizer.Properties;
using System.Diagnostics;
using System.Threading;

namespace BuildVirtualizer
{
    public class QueuingBuildAgent : MarshalByRefObject, Microsoft.TeamFoundation.Build.Common.IBuildAgent
    {
        private static TraceSwitch m_TraceSwitch = new TraceSwitch("General", string.Empty);

        public bool IsBuildInProgress(string teamProject)
        {
            #region Tracing
#line hidden
            if (QueuingBuildAgent.m_TraceSwitch.TraceInfo)
            {
                Trace.TraceInformation(
                    "Queueing Build Agent asked if build in progress for Team Project '{0}'.",
                    teamProject
                    );
            }
#line default
            #endregion

            return false;
        }

        public bool StartBuild(string tfsServer, string teamProject, string buildType, string buildMachine, string buildNumber, string lastBuildNumber, string lastGoodBuildNumber, string buildDirectory, string requestedBy, out string buildUri, out string failureMessage)
        {
            try
            {
                #region Tracing
#line hidden
                if (QueuingBuildAgent.m_TraceSwitch.TraceInfo)
                {
                    Trace.TraceInformation(
                        "Queueing Build Agent asked to start build. Request will be queued instead." +
                        "\nTFS Server = '{0}'" +
                        "\nTeam Project = '{1}'" +
                        "\nBuild Type = '{2}'" +
                        "\nBuild Machine = '{3}'" +
                        "\nBuild Number = '{4}'" +
                        "\nLast Build Number = '{5}'" +
                        "\nLast Good Build Number = '{6}'" +
                        "\nBuild Directory = '{7}'" +
                        "\nRequested By = '{8}'",
                        tfsServer,
                        teamProject,
                        buildType,
                        buildMachine,
                        buildNumber,
                        lastBuildNumber,
                        lastGoodBuildNumber,
                        buildDirectory,
                        requestedBy
                        );
                }
#line default
                #endregion

                BuildQueueItem item = BuildVirtualizerDispatcher.Current.QueueBuild(teamProject, buildType);
                bool startedInline = this.WaitForInlineStart(item);

                if (startedInline)
                {
                    #region Tracing
#line hidden
                    if (QueuingBuildAgent.m_TraceSwitch.TraceInfo)
                    {
                        Trace.TraceInformation(
                            "Build request was started inline." +
                            "\nTFS Server = '{0}'" +
                            "\nTeam Project = '{1}'" +
                            "\nBuild Type = '{2}'" +
                            "\nBuild Machine = '{3}'" +
                            "\nBuild Number = '{4}'" +
                            "\nLast Build Number = '{5}'" +
                            "\nLast Good Build Number = '{6}'" +
                            "\nBuild Directory = '{7}'" +
                            "\nRequested By = '{8}'",
                            tfsServer,
                            teamProject,
                            buildType,
                            buildMachine,
                            buildNumber,
                            lastBuildNumber,
                            lastGoodBuildNumber,
                            buildDirectory,
                            requestedBy
                            );
                    }
#line default
                    #endregion
                    buildUri = item.BuildUri;
                    failureMessage = null;
                    return true;
                }
                else
                {
                    #region Tracing
#line hidden
                    if (QueuingBuildAgent.m_TraceSwitch.TraceInfo)
                    {
                        Trace.TraceInformation(
                            "Build request queued successfully." +
                            "\nTFS Server = '{0}'" +
                            "\nTeam Project = '{1}'" +
                            "\nBuild Type = '{2}'" +
                            "\nBuild Machine = '{3}'" +
                            "\nBuild Number = '{4}'" +
                            "\nLast Build Number = '{5}'" +
                            "\nLast Good Build Number = '{6}'" +
                            "\nBuild Directory = '{7}'" +
                            "\nRequested By = '{8}'",
                            tfsServer,
                            teamProject,
                            buildType,
                            buildMachine,
                            buildNumber,
                            lastBuildNumber,
                            lastGoodBuildNumber,
                            buildDirectory,
                            requestedBy
                            );
                    }
#line default
                    #endregion

                    failureMessage = "Your manual build request has been queued by the build system. Please subscribe to build alerts to be notified when it is completed.";
                    buildUri = null;
                }
            }
            catch (Exception ex)
            {
                #region Tracing
#line hidden
                if (QueuingBuildAgent.m_TraceSwitch.TraceError)
                {
                    Trace.TraceError(
                        "Build requested was not queued successfully." +
                        "\nTFS Server = '{0}'" +
                        "\nTeam Project = '{1}'" +
                        "\nBuild Type = '{2}'" +
                        "\nBuild Machine = '{3}'" +
                        "\nBuild Number = '{4}'" +
                        "\nLast Build Number = '{5}'" +
                        "\nLast Good Build Number = '{6}'" +
                        "\nBuild Directory = '{7}'" +
                        "\nRequested By = '{8}'",
                        "\nException = '{9}'",
                        tfsServer,
                        teamProject,
                        buildType,
                        buildMachine,
                        buildNumber,
                        lastBuildNumber,
                        lastGoodBuildNumber,
                        buildDirectory,
                        requestedBy,
                        ex
                        );
                }
#line default
                #endregion

                throw ex;
            }

            return false;
        }

        private bool WaitForInlineStart(BuildQueueItem item)
        {
            DateTime startTime = DateTime.Now;

            while (true)
            {
                if (item.BuildUri != null) return true;

                TimeSpan waitTime = DateTime.Now - startTime;
                if (waitTime > Settings.Default.InlineTimeout)
                {
                    return false;
                }

                Thread.Sleep(1000);
            }
        }

        public bool StopBuild(string teamProject, string buildNumber, string buildUri)
        {
            return BuildVirtualizerDispatcher.Current.StopBuild(teamProject, buildNumber, buildUri);
        }
    }
}
